package com.ego.goodsweb.listener;

import com.ego.goodsweb.service.GoodsWebService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class GoodsWebListener {

    @Autowired
    private GoodsWebService goodsWebService;

    /** 处理delete的消息
     * 处理insert和update的消息
     * @param spuId spuId
     * @param message message
     * @param channel channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "ego.create.web.queue", durable = "true"),
            exchange = @Exchange(
                    value = "ego.item.exchange",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC),
            key = {"item.insert", "item.update"}))
    public void listenCreate(Long spuId, Message message, Channel channel) throws IOException {
        try {
            if (spuId == null) {
                return;
            }
            Map<String, Object> map = goodsWebService.loadModel(spuId);
            goodsWebService.createStaticHtml(spuId,map);
            //手动确认消费
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        }catch (Exception e){
            //手动拒绝消费(不重新加入队列)
            e.printStackTrace();
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }
    }

    /**
     *
     * @param id id
     * @param message message
     * @param channel channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "ego.delete.web.queue", durable = "true"),
            exchange = @Exchange(
                    value = "ego.item.exchange",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC),
            key = "item.delete"))
    public void listenDelete(Long id, Message message, Channel channel) throws IOException {
        try {
            if (id == null) {
                return;
            }
            // 删除页面
            goodsWebService.deleteHtml(id);
            //手动确认消费
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        }catch (Exception e){
            //手动拒绝消费(不重新加入队列)
            e.printStackTrace();
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }
    }
}
